<template>
  <!-- 服务商推荐 -->
  <CommonTitle titleName="推荐比选服务单位"></CommonTitle>
  <div class="box">
    <el-form :inline="true" label-width="140" :rules="rules" ref="formRef" :model="formInline" class="demo-form-inline">
      <el-row>
        <el-col :span="8" v-if="state.disabled">
          <el-form-item label="审核编号">
            <el-input v-model="formInline.flowId" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="state.disabled">
          <el-form-item label="审核状态">
            <el-select v-model="formInline.status" disabled>
              <el-option v-for="item in state.auditStatus" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="state.disabled">
          <el-form-item label=" ">
            <el-button type="primary" @click="openOa">查看流程审批</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属部门">
            <el-input v-model="formInline.projectDepartment" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属项目集">
            <el-input v-model="formInline.projectSetName" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目集编号">
            <el-input v-model="formInline.projectSetCode" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目负责人">
            <el-input v-model="formInline.responsibleUserName" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属项目">
            <el-input v-model="formInline.projectName" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目编号">
            <el-input v-model="formInline.projectCode" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务来源">
            <el-input v-model="formInline.projectTaskSource" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属阶段">
            <el-input v-model="formInline.projectStage" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务范围">
            <el-date-picker v-model="formInline.startTime" disabled type="daterange" range-separator="-"
              start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" :size="size" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属任务">
            <el-input v-model="formInline.projectTask" disabled placeholder="" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="选聘方式" prop="electionMethod">
            <el-select disabled v-model="formInline.electionMethod" placeholder="">
              <el-option v-for="item in projectTendersWayList" :key="item" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高限价">
            <el-input v-model="formInline.checkPrice" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资金来源">
            <el-input v-model="formInline.fundsSource" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资格要求" prop="qualificationExplain">
            <el-input v-model="formInline.qualificationExplain" :disabled="state.disabled" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实施范围">
            <el-date-picker :disabled="state.disabled" v-model="formInline.executeScope" type="daterange"
              range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"
              :size="size" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="招标项目概括说明">
            <el-input v-model="formInline.projectSummary" disabled type="textarea" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="7" v-if="!state.disabled">
          <el-form-item label="单位名称">
            <el-input :disabled="state.disabled" v-model="state.serviceList.serviceName" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="7" v-if="!state.disabled">
          <el-form-item label="资信情况说明">
            <el-input :disabled="state.disabled" v-model="state.serviceList.creditPosition" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="7" v-if="!state.disabled">
          <el-form-item label="推荐理由说明">
            <el-input :disabled="state.disabled" v-model="state.serviceList.serviceUnitName" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="3" v-if="!state.disabled">
          <el-form-item label="">
            <el-button @click="addRow">添加</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="被推荐单位名单" label-width="180"></el-form-item>
          <tableCom class="table_class" :tableHead="tableHead" :tableData="tableData" :isRadio="false" border
            :height="300" :isSelection="false" style="margin-bottom: 20px;">
            <template #operate>
              <el-table-column label="操作" width="200" align="center" fixed="right">
                <template #default="{ row }">
                  <el-button :disabled="state.disabled" size="small" class="look" type="primary"
                    @click="deleteHandler(row)">删除</el-button>
                </template>
              </el-table-column>
            </template>
          </tableCom>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formInline.remark" :disabled="state.disabled" type="textarea" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="相关附件" prop="files">
            <FileMinioUpload
                    :disabled="state.disabled"
                    :restriction="true"
                    :restrictionLimit="9"
                    @updateFiles="updateFiles"
                    v-model:files="formInline.files"
                    :show-button="!state.disabled"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <CommonTitle titleName="其他信息"></CommonTitle>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请人">
            <el-input disabled v-model="formInline.createName" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请部门">
            <el-input disabled v-model="formInline.createDepartmentName" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="创建时间">
            <el-input disabled v-model="formInline.createTime" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span class="dialog-footer" v-if="!state.disabled">
      <el-button @click="submit">发起审批</el-button>
      <el-button type="primary" @click="goback"> 取消 </el-button>
    </span>
  </div>
</template>

<script setup>
import TableCom from "@/components/table/table.vue";
import FileMinioUpload from "@/components/FileMinioUpload.vue";

import {ref, reactive, onBeforeMount, onMounted, watch, nextTick} from "vue";
import {
  ElRow,
  ElDatePicker,
  ElCol,
  ElMessage,
  ElForm,
  ElFormItem,
  ElInput,
} from "element-plus";
import { serviceApi } from "@/api/project";
import {
  getURLhandler,
  nanoid,
} from "@/views/constructionProjectManage/static/utools.js";

import CommonTitle from "@/components/CommonTitle.vue";
import { useRouter, useRoute } from "vue-router";
import {useSetFormData} from "@/hooks/setFormData";
let router = useRouter();
let route = useRoute();
const state = reactive({
  user: "",
  auditStatus: [
    {
      label: "待审核",
      value: "1",
    },
    {
      label: "审核成功",
      value: "2",
    },
    {
      label: "审核驳回",
      value: "3",
    },
  ],
  serviceList: {
    serviceName: "",
    creditPosition: "",
    serviceUnitName: "",
    serviceId: nanoid(),
  },
  projectTaskId: "",
  itemId: "",
  projectId: "",
  disabled: false,
});
const formInline = reactive({});
const {
    setData,
    getData,
    getAttributeNum,
    filterEmptyAttributes,
} = useSetFormData({
    key:`service-${getURLhandler(route.path).projectId}-${getURLhandler(route.path).projectTaskId}-${getURLhandler(route.path).itemId}`,
});


const tableData = ref([]);
const tableHead = ref([
  {
    prop: "serviceName",
    label: "单位名称",
  },
  {
    prop: "creditPosition",
    label: "资信情况说明",
  },
  {
    prop: "serviceUnitName",
    label: "推荐理由说明",
  },
]);
//删除
const deleteHandler = (row) => {
  tableData.value = tableData.value.filter(
    (item) => item.serviceId !== row.serviceId
  );

  let key = `service-table-${getURLhandler(route.path).projectId}-${getURLhandler(route.path).projectTaskId}-${getURLhandler(route.path).itemId}`;
  setData(tableData.value,key)
};
const handel = () => { };
const addRow = () => {
  state.serviceList.serviceId = nanoid();
  tableData.value.push(JSON.parse(JSON.stringify(state.serviceList)));
  let key = `service-table-${getURLhandler(route.path).projectId}-${getURLhandler(route.path).projectTaskId}-${getURLhandler(route.path).itemId}`;
  setData(tableData.value,key)
};
const goback = () => {
  router.go(-1);
};
const formRef = ref(null);

const updateFiles = () => { };
const submit = () => {
  formRef.value.validate(async (valid, fields) => {
    if (valid) {
      formInline.projectId = state.projectId;
      formInline.taskId = state.projectTaskId;
      formInline.itemId = state.itemId;
      let obj = {};
      obj.applyStartTime = formInline.executeScope[0];
      obj.applyEndTime = formInline.executeScope[1];
      obj.tenderTaskId = formInline.taskId;
      obj.projectId = state.projectId;
      obj.fundsSource = formInline.fundsSource;
      obj.checkPrice = formInline.checkPrice;
      obj.remark = formInline.remark;
      obj.id = formInline.id;
      obj.qualificationExplain = formInline.qualificationExplain;
      obj.electionMethod = formInline.electionMethod;
      obj.serviceList = tableData.value;
      obj.files = formInline.files;
      await serviceApi.serviceAdd(obj).then((res) => {
        if (res.code == "200") {
          ElMessage.success("操作成功");
          router.go(-1);
        }
      });
    }
  });
};
onBeforeMount(() => {
  state.projectTaskId = getURLhandler(route.path).projectTaskId;
  state.projectId = getURLhandler(route.path).projectId;
  state.itemId = getURLhandler(route.path).itemId;
  state.disabled = +getURLhandler(route.path).isLook;
});
// 1, "公开招标
// 2, "公开竞争性谈判
// 3, "公开竞争性磋商
// 4, "择优比选"
// 5, "单一来源采购
// 6, "邀请竞争性谈判
// 7, "邀请竞争性磋商
// 8, "择优询价"
// 9, "单一来源采购
const projectTendersWayList = reactive([
  {
    label: "公开招标",
    value: "1",
  },
  {
    label: "公开竞争性谈判",
    value: "2",
  },
  {
    label: "公开竞争性磋商",
    value: "3",
  },
  {
    label: "择优比选",
    value: "4",
  },
  {
    label: "单一来源采购",
    value: "5",
  },
  {
    label: "邀请竞争性谈判",
    value: "6",
  },
  {
    label: "邀请竞争性磋商",
    value: "7",
  },
  {
    label: "择优询价",
    value: "8",
  },
  {
    label: "单一来源采购",
    value: "9",
  },
]);
const rules = {
  checkPrice: [
    { required: true, message: "最高报价不能为空", trigger: "blur" },
  ],
  qualificationExplain: [
    { required: true, message: "资格要求不能为空", trigger: "blur" },
  ],
  fundsSource: [
    { required: true, message: "资金来源不能为空", trigger: "blur" },
  ],
  executeScope: [
    { required: true, message: "实施范围不能为空", trigger: "blur" },
  ],
  remark: [{ required: true, message: "备注不能为空", trigger: "blur" }],
};
const openOa = () => {
  window.open(formInline.routeUrl);
};

const isBool = ref(false);
watch([()=>state.disabled,()=>formInline],(newVal)=>{
    if(newVal[0]===0 &&  Object.keys(newVal[1]).length > 1 && isBool.value){
        setData(formInline);
    }
},{deep:true})


const getProjectData = () => {
    serviceApi
        .serviceLook({
            taskId: state.projectTaskId,
            itemId: state.itemId,
            projectId: state.projectId,
        })
        .then(async (res) => {
            if (res.code === "200") {
                let obj = {};
                if (getAttributeNum(await getData()) > getAttributeNum(res.data)) { // 缓存中的数据比接口数据的多
                    obj = Object.assign({},await getData(), filterEmptyAttributes(res.data))
                }
                if (getAttributeNum(await getData()) <= getAttributeNum(res.data)) { // 缓存中的数据比接口数据的少或者相同
                    obj = filterEmptyAttributes(res.data)
                }

                for (const key in obj) {
                    if (key === "startTime") {
                        if (state.disabled === 0) {
                            formInline[key] = obj[key] || [];
                        }
                        if (state.disabled === 1) {
                            formInline[key] = [
                                obj[key] || '',
                                obj['endTime'] || ''
                            ];
                        }
                        continue;
                    }
                    if (key === "serviceList") {
                        tableData.value = obj[key] || [];
                        continue;
                    }
                    if (key === "applyStartTime") {
                        formInline["executeScope"] = [
                            res.data["applyStartTime"],
                            res.data["applyEndTime"],
                        ];

                        if (state.disabled === 1) {
                            formInline["executeScope"] = [
                                obj["applyStartTime"],
                                obj["applyEndTime"],
                            ];
                        }
                        continue;
                    }
                    formInline[key] = obj[key];
                }

                await nextTick(() => {
                    isBool.value = true;
                })
            }
        })
}

const getTableData = async () => {
    let key = `service-table-${getURLhandler(route.path).projectId}-${getURLhandler(route.path).projectTaskId}-${getURLhandler(route.path).itemId}`;
    let data = await getData(key);
    for (let key in data) {
        tableData.value.push(data[key]);
    }
}

onMounted(() => {
    getProjectData();
    getTableData();
});
</script>
<style lang="scss" scoped>
.el-form-item,
.el-select {
  width: 100%;
}

.box {
  border-radius: 10px;
  border: 1px solid #e3e7f1;
  padding: 34px 90px;
}
</style>
